﻿//-----------------------------------------------------------------------
// <copyright file="Exists.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// </copyright>
// <author>Andy Reeves</author>
// <email>andyr</email>
// <date>2004-03-23</date>
// <summary>Returns TRUE if a service exists.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Sdc.Tasks.ServiceProcess
{
    using System;
    using Microsoft.Build.Framework;

    /// <summary>
    /// Returns TRUE if a service exists
    /// </summary>
    public class Exists : TaskBase
    {
        private string serviceName;
        private bool serviceExists;
        private bool isDisabled = false;

        /// <summary>
        /// The short name that identifies the service to the system.
        /// </summary>
        /// <value>The short name that identifies the service to the system, e.g. "W3SVC". This service must exist on the local computer.</value>
        [Required]
        public string ServiceName
        {
            get { return (this.serviceName ?? String.Empty); }
            set { this.serviceName = value; }
        }

        /// <summary>
        /// Returns TRUE if the service specified exists
        /// </summary>
        [Output]
        public bool DoesExist
        {
            get { return this.serviceExists; }
        }

        /// <summary>
        /// Returns TRUE if the service is disabled
        /// </summary>
        [Output]
        public bool IsDisabled
        {
            get { return this.isDisabled; }
        }

        /// <summary>
        /// Performs the action of this task.
        /// </summary>
        protected override void InternalExecute()
        {
            #region Execute code

            this.serviceExists = false;

            Log.LogMessageFromResources("Win32Service.Exists", this.serviceName);
            try
            {
                System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(this.serviceName);
                this.isDisabled = Configuration.ServiceProcess.ServiceController.IsDisabled(this.serviceName);
                string status = sc.Status.ToString();
                this.serviceExists = true;
            }
            catch (InvalidOperationException)
            {
                // this will be thrown if the service doesn't exist
                this.serviceExists = false;
            }            
            
            #endregion
        }
      }
}